import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/login/index.vue'
import Home from '@/views/home/index.vue'
import ArticleManage from '@/views/article/ArticleManage.vue'
import { useUserStore } from '@/stores/modules/user.js'
import NotFound from '@/components/NotFound.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: Login
    },
    {
      path: '/',
      component: Home,
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          component: ArticleManage
        },
        {
          path: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        }
      ]
    },
    // plan on directly navigating to the not-found route using its name
    { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound },
    // if you omit the last `*`, the `/` character in params will be encoded when resolving or pushing
    { path: '/:pathMatch(.*)', name: 'bad-not-found', component: NotFound }
  ]
})
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
    return
  }
  const userStore = useUserStore()
  if (userStore.token === '') {
    next('/login')
  } else {
    next()
  }
})
export default router
